package com.hex.liyue.storemodule.presenter;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.hex.liyue.LiYueApplication;
import com.hex.liyue.commonmodule.manager.HttpManager;
import com.hex.liyue.commonmodule.manager.UserManager;
import com.hex.liyue.commonmodule.net.ResponseListener;
import com.hex.liyue.commonmodule.utils.L;
import com.hex.liyue.commonmodule.utils.PayResult;
import com.hex.liyue.commonmodule.utils.SignUtils;
import com.hex.liyue.commonmodule.utils.T;
import com.hex.liyue.commonmodule.view.IosInputDialog;
import com.hex.liyue.storemodule.bean.PayOrderDetailsResultBean;
import com.hex.liyue.usermodule.bean.OrderDetailsResultBean;
import com.hex.liyue.wxapi.WeChatPayUtils;
import com.tencent.mm.sdk.openapi.IWXAPI;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created by WJ on 2016/6/29.
 * 这是一个支付界面的业务
 */
public class PaymentOrdersPresenter {
    private IPaymentOrdersView iPaymentOrdersView;
    private final int SDK_PAY_FLAG = 1;
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        iPaymentOrdersView.showT("支付成功");
                        iPaymentOrdersView.startActivityOrderDetails();
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            iPaymentOrdersView.showT("支付结果确认中");
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            iPaymentOrdersView.showT("支付失败");
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };
    private IWXAPI msgApi;

    public PaymentOrdersPresenter(IPaymentOrdersView iPaymentOrdersView) {
        this.iPaymentOrdersView = iPaymentOrdersView;
    }

    public void orderPay(String orderId, final int type, final Activity activity, String password, final String name, final String desc) {
        iPaymentOrdersView.showLod("加载中...");
        HttpManager.getInstance().orders_pay(UserManager.getUserId(), orderId, password, type, new ResponseListener<PayOrderDetailsResultBean>() {
            @Override
            public void onSuccess(PayOrderDetailsResultBean payOrderDetailsResultBean) {
                iPaymentOrdersView.closeLod();
                if (type == 1) {
                    //余额支付
                    iPaymentOrdersView.startActivityOrderDetails();
                } else if (type == 2) {
                    //微信支付
                    wechatpay(activity, payOrderDetailsResultBean);
                    //  T.show(LiYueApplication.getInstance(),"陛下！此支付暂未开放",0);
                } else if (type == 3) {
                    //支付宝支付
                    payAlipay(activity, payOrderDetailsResultBean, name, desc);
                }
            }


            @Override
            public void onFailure(String responseresult) {
                iPaymentOrdersView.closeLod();
                T.show(LiYueApplication.getInstance(), responseresult, 0);
                iPaymentOrdersView.showT(responseresult);
            }
        });
    }

    /**
     * 这是一个微信支付的方法
     *
     * @param activity
     * @param payOrderDetailsResultBean
     */
    private void wechatpay(Activity activity, PayOrderDetailsResultBean payOrderDetailsResultBean) {
//        msgApi = WXAPIFactory.createWXAPI(activity, Constant.APP_ID);
//        // 将该app注册到微信
//        msgApi.registerApp(Constant.APP_ID);
        WeChatPayUtils.getInstance().pay(activity, payOrderDetailsResultBean.data.wechat.prepay_id);
//        PayReq request = new PayReq();
//        //appid
//        request.appId = Constant.APP_ID;
//        L.e("微信", payOrderDetailsResultBean.data.wechat.appid);
//        //商户号
//        request.partnerId = Constant.MCH_ID;
//        L.e("微信", payOrderDetailsResultBean.data.wechat.mch_id);
//        //会话id
//        request.prepayId = payOrderDetailsResultBean.data.wechat.prepay_id;
//        L.e("微信", payOrderDetailsResultBean.data.wechat.prepay_id);
//        //扩展字段
//        request.packageValue = "Sign=WXPay";
//        //随机字符串
//        request.nonceStr = payOrderDetailsResultBean.data.wechat.nonce_str;
//        L.e("微信", payOrderDetailsResultBean.data.wechat.nonce_str);
//        //时间戳
//        request.timeStamp = payOrderDetailsResultBean.data.request_time;
//        L.e("微信", payOrderDetailsResultBean.data.request_time);
//        // 签名
//        request.sign = payOrderDetailsResultBean.data.wechat.sign;
//        L.e("微信", payOrderDetailsResultBean.data.wechat.sign);
//        //request.extData = "app data"; // optional
//        iPaymentOrdersView.showT("掉起支付");
//        msgApi.sendReq(request);
    }


    /**
     * 展示输入密码的对话框
     *
     * @param activity
     */
    public void showinputpassworddialog(final String orderId, final int type, final Activity activity, final String name, final String desc) {
        IosInputDialog iosInputDialog = new IosInputDialog(activity);
        iosInputDialog.show();
        iosInputDialog.setOnButtonClickListener(new IosInputDialog.OnButtonClickListener() {
            @Override
            public void onOkClickListener(String text) {
                if (TextUtils.isEmpty(text)) {
                    iPaymentOrdersView.showT("密码不能为空");
                    return;
                }
                orderPay(orderId, type, activity, text, name, desc);
            }

            @Override
            public void onCancelClickListener() {

            }
        });
    }

    /**
     * 支付宝支付
     */
    private void payAlipay(final Activity activity, final PayOrderDetailsResultBean payOrderDetailsResultBean, final String name, final String desc) {
        Runnable payRunable = new Runnable() {
            @Override
            public void run() {
                //g构造paytask
                PayTask alipay = new PayTask(activity);
                //调用支付接口,获取支付结果
                String orderInfo = getOrderInfo(payOrderDetailsResultBean.data.alipay.pid, payOrderDetailsResultBean.data.alipay.seller,
                        payOrderDetailsResultBean.data.order_sn,
                        name, desc, payOrderDetailsResultBean.data.pay_money + "", payOrderDetailsResultBean.data.alipay.notify);
                /**
                 * 特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中！
                 */
                String sign = sign(orderInfo, payOrderDetailsResultBean.data.alipay.private_key);

                try {
                    /**
                     * 仅需对sign 做URL编码
                     */
                    sign = URLEncoder.encode(sign, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                /**
                 * 完整的符合支付宝参数规范的订单信息
                 */
                final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);

            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunable);
        payThread.start();
    }

    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    private String sign(String content, String RSA_PRIVATE) {
        L.i("私有密钥", RSA_PRIVATE);
        return SignUtils.sign(content, RSA_PRIVATE);
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    private String getSignType() {
        return "sign_type=\"RSA\"";
    }

    /**
     * 这是一个获取订单详情的方法
     *
     * @param orderId
     */
    public void getOrderDetails(String orderId) {
        iPaymentOrdersView.showLod("加载中...");
        HttpManager.getInstance().orders_detail(UserManager.getUserId(), orderId, new ResponseListener<OrderDetailsResultBean>() {
            @Override
            public void onSuccess(OrderDetailsResultBean orderDetailsResultBean) {
                iPaymentOrdersView.closeLod();
                iPaymentOrdersView.setInfo(orderDetailsResultBean.data);
            }

            @Override
            public void onFailure(String responseresult) {
                iPaymentOrdersView.closeLod();
                iPaymentOrdersView.showT(responseresult);
            }
        });
    }

    /**
     * 这是一个拼接信息的方法
     *
     * @param pid       签约者合作者id
     * @param seller    支付宝账号
     * @param tradeno   订单号
     * @param body      商品详情
     * @param subject   商品名称
     * @param price     商品单价
     * @param notifyurl 通知url
     * @return
     */
    private String getOrderInfo(String pid, String seller, String tradeno, String body, String subject, String price, String notifyurl) {

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + pid + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + seller + "\"";

        // 商户网站唯一订单号Å
        orderInfo += "&out_trade_no=" + "\"" + tradeno + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + subject + "\"";

        // 商品详情
        orderInfo += "&body=" + "\"" + body + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + price + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + notifyurl + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }
}
